﻿using PivotData;
using System.Linq;

namespace PivotIO.XML
{
    /// <summary>
    /// Store the category info in the proper place.
    /// </summary>
    public class FacetCategoryIO : PerCollectionDataIO<FacetCategory>
    {
        static FacetCategoryIO()
        {
            IOName = "Categories.xml";
        }

        /// <summary>
        /// Save all the facets that need to be saved. Only save if there are changes vs what we currently have in cache.
        /// </summary>
        /// <param name="collectionID"></param>
        /// <param name="categories"></param>
        public static void SaveAllFacets(int collectionID, FacetCategory[] categories)
        {
            if (_cache.Keys.Contains(collectionID))
            {
                var oldFacets = _cache[collectionID];
                if (oldFacets != null)
                {
                    if (FacetsAreEqual(oldFacets, categories))
                        return;
                }
            }
            SaveAll(collectionID, categories);
        }

        /// <summary>
        /// Check to see if two sets of facet categories are equal or not.
        /// </summary>
        /// <param name="oldFacets"></param>
        /// <param name="categories"></param>
        /// <returns></returns>
        private static bool FacetsAreEqual(FacetCategory[] oldFacets, FacetCategory[] categories)
        {
            if (oldFacets.Length != categories.Length)
                return false;

            return (from f1 in categories
                    join f2 in oldFacets on f1 equals f2
                    select f1.Name).Count() == categories.Length;
        }

        /// <summary>
        /// Return all facets
        /// </summary>
        /// <param name="collectionID"></param>
        /// <returns></returns>
        public static FacetCategory[] LoadAllFacets(int collectionID)
        {
            return LoadAll(collectionID);
        }
    }
}
